package model.beans;

import core.Database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;

/**
 * RouterBean converter. 
 * It is needed for the list of routers on explorer.xhtml page. 
 * @author Danon
 */
@FacesConverter("data.RouterBeanConverter")
public class RouterBeanConverter implements Converter {

    private static final Logger logger = Logger.getLogger(RouterBeanConverter.class);
    
    /**
     * Converts string value (containing the id of the router) to RouterBean object.
     * @param value Router id as string
     * @return RouterBean object with specified id.
     */
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        RouterBean r = null;
        if (value==null) return null;
        if(value.equals("")) return 0;
        try {
            Connection c = Database.getInstance().getConnection();
            try (PreparedStatement ps = c.prepareStatement("select router_id, title from routers where router_id = ?")) {
                ps.setInt(1, Integer.parseInt(value));
                ResultSet rs = ps.executeQuery();
                if(rs.next()) {
                    r = new RouterBean(rs.getInt("router_id"), rs.getString("title"));
                }
            }
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
        }
        return r;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if(value==null) return "";
        return value.toString();
    }
    
}
